import jsrsasign from './jsrsasign.js';
import base64 from './base64.js';
import {
	oApiList
} from './info.js';

// 物联网平台加密
const fDigestData = (data = {}, agent_id = 0) => {
	const arr = []
	const {
		api_id,
		api_secret
	} = oApiList[agent_id]
	const obj = {
		...data,
		api_id,
		timestamp: parseInt(new Date() / 1000)
	}
	for (let key in obj) {
		arr.push(key)
	}
	arr.sort()
	const newArr = arr.map(key => {
		return key + '=' + obj[key]
	})

	const md = new jsrsasign.crypto.MessageDigest({
		'alg': 'sha256',
		'prov': 'cryptojs'
	});
	let str = newArr.join('&') + api_secret
	md.updateString(base64.encode(str))
	obj.sign = md.digest()

	return obj
}

// 随机数
const fNonceStr = (max = 32, index = 62) => {
	const arr = [
		'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
		'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
		'v', 'w', 'x', 'y', 'z',
		'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
		'V', 'W', 'X', 'Y', 'Z'
	]
	let str = ''
	for (var i = 0; i < max; i++) {
		str += arr[parseInt(Math.random() * index)]
	}
	return str
}


// 如果没有通过拦截器配置域名的话，可以在这里写上完整的URL(加上域名部分)
const sUrl = 'https://cs.mqlinks.com/'
// 此处第二个参数vm，就是我们在页面使用的this，你可以通过vm获取vuex等操作，更多内容详见uView对拦截器的介绍部分：
const install = (Vue, vm) => {

	const login = (code) => vm.$u.get(sUrl + 'wxpay/openid', {
		code
	})

	// 查询ip
	const getcallbackip = (JSCODE) => {
		vm.$u.get('https://pv.sohu.com/cityjson?ie=utf-8', {}, {
			// 'content-type': 'application/x-www-form-urlencoded'
		}).then(data => {
			console.log(data)
		})
	}

	const getSimCardDetail = (iccids) => vm.$u.post(sUrl + 'api/customer/v1/sim_cards/get_sim_card_detail',
		fDigestData({
			iccids
		}), {
			'content-type': 'application/x-www-form-urlencoded'
		})

	const simCardRenew = (iccids, cycle_number, agent_id) => vm.$u.post(sUrl + 'api/customer/v1/sim_cards/renew',
		fDigestData({
			iccids,
			cycle_number
		}, agent_id), {
			'content-type': 'application/x-www-form-urlencoded'
		})


	const wxPay = (amount = 1, description = '测试') => {
		return vm.$u.post(sUrl + 'wxpay/js_prepay', {
			orderNum: fNonceStr(),
			amount,
			openId: vm.vuex_token,
			description
		}, {
			// 'content-type': 'application/x-www-form-urlencoded'
		})
	}
	// 将各个定义的接口名称，统一放进对象挂载到vm.$u.api(因为vm就是this，也即this.$u.api)下
	vm.$u.api = {
		login,
		getSimCardDetail,
		simCardRenew,
		getcallbackip,
		wxPay
	};
}

export default {
	install
}
